package cn.tedu.sgs.record.service.impl;

import cn.tedu.sgs.record.mapper.RecordMapper;
import cn.tedu.sgs.record.mapper.RecordUserMapper;
import cn.tedu.sgs.record.pojo.dto.RecordReviewDTO;
import cn.tedu.sgs.record.pojo.dto.RecordSaveParam;
import cn.tedu.sgs.record.pojo.dto.RecordQuery;
import cn.tedu.sgs.record.pojo.entity.Record;
import cn.tedu.sgs.record.pojo.vo.RecordVO;
import cn.tedu.sgs.record.service.RecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class RecordServiceImpl implements RecordService {

	@Autowired
	private RecordMapper recordMapper;

	@Autowired
	private RecordUserMapper userMapper;

	@Override
	public List<RecordVO> selectRecord(RecordQuery recordQuery) {
		log.debug("查询投放记录: {}", recordQuery);
		List<RecordVO> list = recordMapper.selectRecord(recordQuery);
		return list;
	}

	@Override
	public void saveRecord(RecordSaveParam recordSaveParam) {
		log.debug("保存投放记录:{}",recordSaveParam);
		Record record = new Record();
		BeanUtils.copyProperties(recordSaveParam,record);
		if (recordSaveParam.getCreateTime() == null) {
			record.setCreateTime(new Date());
		}
		record.setStatus(10);
		record.setPoints(0);
		recordMapper.insert(record);
	}

	@Override
	public List<RecordVO> selectById(RecordQuery recordQuery) {
		log.debug("投放记录: {}", recordQuery);
		List<RecordVO> list = recordMapper.selectById(recordQuery);
		return list;
	}

	@Override
	public void deleteRecord(Long id) {
		log.debug("删除投放记录: {}", id);
		recordMapper.deleteById(id);
	}

	@Override
	@Transactional
	public void reviewRecord(RecordReviewDTO reviewDTO) {
		// 1. 更新记录状态
		Record record = new Record();
		record.setId(reviewDTO.getId());
		record.setStatus(reviewDTO.getStatus());
		recordMapper.updateById(record);

		// 2. 如果是审核通过且指定了积分，则增加用户积分
		if (reviewDTO.getStatus() == 20 && reviewDTO.getPoints() != null && reviewDTO.getPoints() > 0) {
			// 先查询记录获取用户ID
			Record reviewedRecord = recordMapper.selectRecordById(reviewDTO.getId());
			if (reviewedRecord != null) {
				// 增加用户积分
				userMapper.addPoints(reviewedRecord.getUserId(), reviewDTO.getPoints());
			}
		}
	}
}